'use strict';

const Service = require('egg').Service;
const AdminRolesModel = require('../../model/AdminRolesModel');
const AdminRoleMenuRelModel = require('../../model/AdminRoleMenuRelModel');
const adminRolesModel = new AdminRolesModel();
const adminRoleMenuRelModel = new AdminRoleMenuRelModel();

/**
 * 创建者: rliang
 * 创建时间: 2019年08月23日 15:35:28
 * 功能描述: 管理用户角色
 */
class AdminRolesService extends Service {
  
  /**
   * 根据条件查询角色列表（支持分页）
   * @param {string} name 角色名称
   * @param {int} pageSize 一页显示多少条
   * @param {int} pageIndex 当前页数
   */
  async queryAdminRolesList(name, pageSize, pageIndex) {
    // 查询
    const adminRolesList = await adminRolesModel.selectAdminRolesList(this.app, { name, pageSize, pageIndex });

    if (adminRolesList && adminRolesList.length > 0) {
      return adminRolesList;
    }
    return null;
  }

  async queryAdminRolesListCount(name) {
    return await adminRolesModel.selectAdminRolesListCount(this.app, name);
  }

  async addAdminRole(entity) {
    let _adminRole = new adminRolesModel.entity();
    // 组装角色信息
    _adminRole = entity;
    _adminRole.state = 1;
    _adminRole.creator = this.ctx.curAdminUser.id;
    _adminRole.createTime = this.ctx.getDate_YYYYMMDDHHmmss();
    _adminRole.updateTime = this.ctx.getDate_YYYYMMDDHHmmss();
    
    const result = await adminRolesModel.insert(this.app, _adminRole);
    
    return result;
  }

  // 修改角色信息
  async updateAdminRole(request) {
    let _adminRole = new adminRolesModel.entity();
    // 组装角色信息
    _adminRole = request;
    _adminRole.updateTime = this.ctx.getDate_YYYYMMDDHHmmss();
    return await adminRolesModel.updateById(this.app, _adminRole);
  }

  async queryAdminRole(id) {
    const result = await this.app.mysql.select('admin_user_role_rel', {
      where: {
        role_id: id,
      },
    });
    return result;
  }

  async setRoleAutho(roleId, menus) {
    const conn = await this.app.mysql.beginTransaction(); // 初始化事务
    try {

      await adminRoleMenuRelModel.deleteByRoleId_transaction(conn, roleId);
      const entitys = [];
      for (const menu of menus) {
        entitys.push({ 
          roleId, 
          menuId: menu.menuId,
          defaultRightsType: menu.defaultRightsType,
          creator: this.ctx.curAdminUser.id,
          create_time: this.ctx.getDate_YYYYMMDDHHmmss(),
          update_time: this.ctx.getDate_YYYYMMDDHHmmss(),
        });
      }
      await adminRoleMenuRelModel.insertBatch_transaction(conn, entitys);

      await conn.commit(); // 提交事务

      return true;
    } catch (err) {
      // error, rollback
      await conn.rollback(); // 一定记得捕获异常后回滚事务！！
      this.logger.error('更新角色权限失败（操作数据库失败）', err);
      return false;
    }
  }

  async deleteRoleMenusRel(roleId) {
    // 删除该角色的所有菜单。    
    return await adminRoleMenuRelModel.deleteByRoleId(this.app, roleId);
  }

  async insertRoleMenusRes(entitys) {
    return await adminRoleMenuRelModel.insert(this.app, entitys);
  }

  // 删除角色信息(逻辑删除)
  async deleteAdminRole(result) {
    const _adminUser = new adminRolesModel.entity();
    _adminUser.id = result.id;
    _adminUser.state = 0;
    return await adminRolesModel.updateById(this.app, _adminUser);
  }

}

module.exports = AdminRolesService;
